#!/bin/sh


function checkIsOk() {
   # $1 操作名

   if [[ $? > 0 ]]; then
      echo "[${1}] is failed"
      exit 1
   fi
   echo "[${1}] is success"
}

function restartServer() {
   # $1 服务名

   export GOPATH='/root/aist/goProject'
   export GO111MODULE='on'
   export GOPROXY='https://goproxy.cn'
   # kill 老的服务
   psServerCmd=$(ps -ef | grep "${1}" | grep -v grep)
   oldPid=$(echo ${psServerCmd} | awk '{print $2}')
   echo "kill ps: ${psServerCmd}"
   echo "old server pid: ${oldPid}"
   if [[ $oldPid > 0 ]]; then
      kill -9 $oldPid
   fi
   sleep 1

   # 启动服务
   nohup ./$1 >>./out.log 2>&1 &
   sleep 1

   # 获取启动的服务的 pid, 判断是否成功, 前后两个命令需要一致
   psServerCmd=$(ps -ef | grep "${1}" | grep -v grep)
   serverPid=$(echo ${psServerCmd} | awk '{print $2}')
   echo "strat ps: ${psServerCmd}"
   echo "new server pid: ${serverPid}"
   if [[ $serverPid == "" ]]; then
      echo "服务: ${1} 启动失败!!!"
      exit 1
   fi
   echo "启动服务: ${1} 成功"
}

function main() {
   # $1 项目路径
   # $2 服务名

   git pull origin master
   checkIsOk "git pull"

   # 处理后端服务
   printf "=================== 开始处理后端 =======================\n"
   cd "${1}/app_go"
   go build -o=$2 main.go
   checkIsOk "go build"
   restartServer $2 # 启动
   printf "=================== 后端处理结束 =======================\n"

   # 处理前端
   printf "=================== 开始处理前端 =======================\n"
   cd "${1}/mycrm_vue"
   npm install
   checkIsOk "npm install"

   npm run build
   checkIsOk "npm run build"

   # 删除老的文件
   webPackageName="mycrmweb"
   webPath="/usr/share/nginx/www/${webPackageName}"
   rm -rf $webPath
   mv $webPackageName $webPath
   checkIsOk "mv mycrmweb ${webPath}"
   printf "=================== 处理前端结束 =======================\n"
}

# 入口
projectPath=$(pwd)
main $projectPath "mycrm"

